package com.socket.secure.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.ServletRequestPathUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
public class MappingUtil implements ApplicationListener<WebServerInitializedEvent> {
    private static RequestMappingHandlerMapping mapping;

    /**
     * Gets the mapping of the current request URI {@link Method} <br>
     *
     * @param request {@link HttpServletRequest}
     * @return If no matching controller is found or no annotation is specified, null is returned
     */
    public static HandlerMethod getHandlerMethod(HttpServletRequest request) {
        try {
            ServletRequestPathUtils.parseAndCache(request);
            HandlerExecutionChain chain = mapping.getHandler(request);
            if (chain != null) {
                return (HandlerMethod) chain.getHandler();
            }
        } catch (Exception e) {
            // ignore
        } finally {
            ServletRequestPathUtils.clearParsedRequestPath(request);
        }
        return null;
    }

    /**
     * The result is converted to a JSON string (compatible with enumeration conversion)
     */
    public static String toJSONString(Object obj) {
        if (obj instanceof Enum) {
            JSONObject json = new JSONObject();
            BeanUtil.descForEach(obj.getClass(), prop -> {
                json.set(prop.getFieldName(), prop.getValue(obj));
            });
            return json.toString();
        }
        return JSONUtil.toJsonStr(obj);
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        mapping = event.getApplicationContext().getBean(RequestMappingHandlerMapping.class);
    }
}
